/*
 * ServerGUI.java
 *
 * Created on November 5, 2007, 11:23 AM
 */

package legoserver;
import java.util.*;
import org.netbeans.lib.awtextra.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;

/**
 *
 * Authors:
 * Daniel Van Eck
 * Nathan Ver Beek
 */
public class ServerGUI extends javax.swing.JFrame {
    
    private ClientConnection client;
    private RobotConnection robot;
    private LegoMazePathfinder pFinder;
    //private VideoServer videoServer; 
    
    /**
     * Creates new form ServerGUI
     */
    public ServerGUI() {
        initComponents();
        showDate();
        
        this.setVisible(true);
        
        update ("Starting robot thread...");
        robot = new RobotConnection(this);
        robot.start();
        
        update("Starting client thread...");
        client = new ClientConnection (this);
        //client.start();
        
        update("Starting pathfinder thread...");
        pFinder = new LegoMazePathfinder(this);
        pFinder.start();
        
        
        //this.client.startStreamingServer(this);
    }
    
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        tOut = new javax.swing.JTextArea();
        bShutdown = new javax.swing.JButton();
        bKillRobot = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        getContentPane().setLayout(new AbsoluteLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Louie Server");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("serverGuiFrame");
        setResizable(false);
        tOut.setBackground(new java.awt.Color(0, 0, 0));
        tOut.setColumns(20);
        tOut.setEditable(false);
        tOut.setFont(new java.awt.Font("Monospaced", 0, 12));
        tOut.setForeground(new java.awt.Color(255, 255, 255));
        tOut.setRows(5);
        jScrollPane1.setViewportView(tOut);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 460, 260));
        bShutdown.setText("Shutdown");
        bShutdown.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bShutdownMouseClicked(evt);
            }
        });

        getContentPane().add(bShutdown, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 280, -1, -1));

        bKillRobot.setText("Kill Robot");
        bKillRobot.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bKillRobotMouseClicked(evt);
            }
        });

        getContentPane().add(bKillRobot, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 280, -1, -1));
        
        jLabel1.setText("     ");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 300, 20, -1));

        pack();
    }

    private void bShutdownMouseClicked(java.awt.event.MouseEvent evt) {
        if(bShutdown.isEnabled()) {
            bShutdown.setEnabled(false);
            try {
                /*if(videoServer != null) { 
                 update("Shutting down VideoServer connection...");
                 videoServer.stopStream();
                }*/

                update("Shutting down Client connection...");
                client.disconnect();
                client.join(500);

                update("Shutting down Robot connection...");
                try {
                    if(robot.isConnected())
                        robot.disconnect();
                }catch (IOException e) {
                    update("Caught exception when attempting to disconnect robot.");
                }catch (NullPointerException e) {
                    update("Robot connections unitialized.");
                }
                
                if (robot.isConnected())
                    robot.join(500);
                
                update("Shutting down pathfinder...");
                pFinder.shutdown();
                pFinder.join(500);
                
            }
            catch(InterruptedException e) {
                update("Failed to wait for thread exit.");
            }
            //If any threads are still open, this will force their
            //(ungraceful) exit.
            System.exit(0);
        }
    }
    
    private void bGrabFrameMouseClicked(java.awt.event.MouseEvent evt) {
        //for now, tell the client backend to grab a frame
        /*Image i;
        try {
            i = client.getVideoServer().grabFrame();
        }catch(IOException e) {
            update("Failed to grab frame.");
            return;
        }
        
        BufferedImage buffImg = new BufferedImage(i.getWidth(null), i.getHeight(null), BufferedImage.TYPE_INT_RGB);
        //Graphics2D g = buffImg.createGraphics();
        //g.drawImage(img, null, null);
        // Save image to disk as PNG
        try {
            ImageIO.write(buffImg, "jpg", new File("c:\\webcam.jpg"));
        }catch(IOException e) {
            update("Failed to write frame to file.");
            return;
        }*/
    }
    
    private void bKillRobotMouseClicked(java.awt.event.MouseEvent evt) {
        if(bKillRobot.isEnabled()) {
            bKillRobot.setEnabled(false);

            update("Killing the robot...");
            try {
                if(robot.isConnected())
                    robot.sendCmd("shutdown");
            }catch(IOException e) {
                update("Failed to send shutdown cmd.");
            }
        }
    }
    
    public RobotConnection getRobotConnection() {
        if(robot.isBusy())
            return null;
        
        return robot;
    }
    
    public ClientConnection getClientConnection() {
        return client;
    }
    
    public LegoMazePathfinder getLegoMazePathfinder() {
        return pFinder;
    }
    
    private void showDate() {
        Calendar c = Calendar.getInstance();
        int hr = c.get(Calendar.HOUR);
        if (hr == 0)
            hr = 12;
        int mn = c.get(Calendar.MINUTE);
        String min = new Integer(mn).toString();
        if(mn >= 0 && mn <= 9)
            min = "0" + min;
        String ampm;   
        if(c.get(Calendar.AM_PM) == 1)
            ampm = "PM";
        else
            ampm = "AM";
        String time = hr + ":" + min + " " + ampm + " | ";
        
        
        int day = c.get(Calendar.DAY_OF_MONTH);
        int month = c.get(Calendar.MONTH) + 1;
        int year = c.get(Calendar.YEAR);
        String date = month + "/" + day + "/" + year;
        
        update(time + date);
    }
    
    public void update(String s) { 
        System.out.println(s);
        tOut.append(s + "\n");
        tOut.setCaretPosition(tOut.getDocument().getLength());
    }
    
    
    private javax.swing.JButton bShutdown;
    private javax.swing.JButton bKillRobot;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea tOut;
    
}
